const tags = ['api', 'user']
const Joi = require('joi')
const JWT = require('jsonwebtoken');
const decryptData = require('../../utils/decrypted-data');
const {
  users
} = require("../../models")
const {
  getReq
} = require('../../utils/req')
const {
  appid,
  secret
} = require('../../config')
module.exports = [{
  method: 'POST',
  path: `/user/wxLogin`,
  handler: async (req, h) => {
      const {
        code,
        encryptedData,
        iv
      } = req.payload

      const res = await getReq('https://api.weixin.qq.com/sns/jscode2session', {
        appid,
        secret,
        js_code: code,
        grant_type: 'authorization_code'
      })
      return res
      const {
        openid,
        session_key: sessionKey
      } = res.data;
      const user = await users.findOrCreate({
        where: {
          open_id: openid
        }
      })

      const userInfo = decryptData(encryptedData, iv, sessionKey, appid)
      await users.update({
        nick_name: userInfo.nickName,
        gender: userInfo.gender,
        avatar_url: userInfo.avatarUrl,
        open_id: openid,
        session_key: sessionKey,
      }, {
        where: {
          open_id: openid
        }
      })
      const token=generateJWT({userId:user[0].id})
      return {
        token
      }
    },
    config: {
      auth: false,
      tags: tags,
      validate: {
        payload: {
          code: Joi.string().required().description('微信用户登录的临时code'),
          encryptedData: Joi.string().required().description('微信用户信息encryptedData'),
          iv: Joi.string().required().description('微信用户信息iv'),
        }
      }
    }
}]


// 签发 jwt
  const generateJWT = (jwtInfo) => {
    const payload = {
      userId: jwtInfo.userId,
      exp: Math.floor(new Date().getTime() / 1000) + 7 * 24 * 60 * 60,
    };
    return JWT.sign(payload, config.jwtSecret);
  }
